import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {AccountService} from '../../account.service';
import {NzMessageService} from 'ng-zorro-antd';
import {Router} from '@angular/router';
import {Observable} from 'rxjs/Observable';
import {isInteger} from '@ng-bootstrap/ng-bootstrap/util/util';

@Component({
  selector: 'app-user-info-edit',
  templateUrl: './user-info-edit.component.html',
  styleUrls: ['./user-info-edit.component.scss'],
  providers: [AccountService]
})
export class UserInfoEditComponent implements OnInit {
  validateForm: FormGroup;
  _isSpinning = false;
  provinceOptions = [];
  cityOptions = [];
  hadGeCityList = false;
  regionOptions = [];
  hadGetRegionList = false;
  typeOptions = [];
  hadInfo = false;
  Province;
  City;
  Region;

  constructor(private fb: FormBuilder,
              private accountService: AccountService,
              private _message: NzMessageService,
              private router: Router) { }

  _submitForm() {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[ i ].markAsDirty();
    }
    if (this.validateForm.valid) {
      this.provinceOptions.forEach(val => {
        if (val.code === this.validateForm.value.Province) {
          this.Province = val.name;
        }
      });
      this.cityOptions.forEach(val => {
        if (val.code === this.validateForm.value.City) {
          this.City = val.name;
        }
      });
      this.regionOptions.forEach(val => {
        if (val.code === this.validateForm.value.Region) {
          this.Region = val.name;
        }
      });
      const body = {
        company_address_detail: `${this.Province} ${this.City} ${this.Region}`,
        company_address_code: this.validateForm.controls['Region'].value,
        class: `[${this.validateForm.value.class}]`,
        company_name: this.validateForm.value.company_name,
        contacts: this.validateForm.value.contacts,
        contacts_mobile: this.validateForm.value.contacts_mobile,
      };
      this._isSpinning = true;
      this.accountService.editUserInfo(body).subscribe((res) => {
        this._isSpinning = false;
        if (res.code === 2000) {
          this._message.success('基本信息修改成功！');
          setTimeout(() => {
            this.router.navigate(['/member/account/user']);
          });
        } else {
          this._message.error(res.message);
        }
      });
    }
  }

  getCaptcha(e: MouseEvent) {
    e.preventDefault();
  }

  ngOnInit() {
    this.validateForm = this.fb.group({
      company_name: [ null, [ Validators.required ] ],
      class: [ null, [ Validators.required ] ],
      Province: [ null, [ Validators.required ] ],
      City: [ null, [ Validators.required ] ],
      Region: [ null, [ Validators.required ] ],
      contacts: [ null, [ Validators.required ] ],
      contacts_mobile: [ null, [ Validators.required ], [this.mobileValidator] ],
    });

    this.validateForm.controls.Province.valueChanges
      .subscribe(res2 => {
        if (!res2) {
          // return;
        } else {
          this.getCityList();
        }
      });

    this.validateForm.controls.City.valueChanges
      .subscribe(res2 => {
        if (!res2) {
          // return;
        } else {
          this.getRegionList();
        }
      });

    this.getUserInfo();

    this.getBusinessTypeList();

    this.getProvinceList();
  }

  mobileValidator = (control: FormControl): any => {
    return Observable.create(function (observer) {
      setTimeout(() => {
       if (!(/(^1[3|4|5|7|8]\d{9}$)|(^09\d{8}$)/).test(control.value)) {
          observer.next({error: true, mobile: true});
        } else {
         observer.next(null);
       }
        observer.complete();
      }, 500);
    });
  }

  getFormControl(name) {
    return this.validateForm.controls[ name ];
  }

  getProvinceList() {
    this.accountService.getProvinceList().subscribe(res => {
      this.provinceOptions = res.data;
    });
  }

  getCityList() {
    this.accountService.getCityList(this.validateForm.controls['Province'].value).subscribe(res => {
      this.cityOptions = res.data;
      if (!this.hadGeCityList) {
        this.hadGeCityList = true;
      } else {
        this.validateForm.controls.City.reset();
      }
    });
  }

  getRegionList() {
    this.accountService.getRegionList(this.validateForm.controls['City'].value).subscribe(res => {
      this.regionOptions = res.data;
      if (!this.hadGetRegionList) {
        this.hadGetRegionList = true;
      } else {
        this.validateForm.controls.Region.reset();
      }
    });
  }

  getBusinessTypeList() {
    this.accountService.getAllClass().subscribe(res => {
      this.typeOptions = res.data;
    });
  }

  getUserInfo() {
    this._isSpinning = true;
    this.accountService.getUserInfo().subscribe(res => {
      if (res.code === 2000) {
        console.log(res);
        const merchant_info = res.data;

        if (merchant_info.class[0] && merchant_info.address_info) {
          this.validateForm.setValue({
            company_name: merchant_info.company_name,
            class: merchant_info.class[0].first_class.id,
            Province: merchant_info.address_info.province.code,
            City: merchant_info.address_info.city.code,
            Region: merchant_info.address_info.region.code,
            contacts: merchant_info.contacts,
            contacts_mobile: merchant_info.contacts_mobile,
          });
        } else {
          console.log('无用户信息');
        }

        this.hadInfo = true;
        this._isSpinning = false;

      } else {
        this._message.error(res.message);
      }
    });
  }
}
